<template>
  <div class="upload">
    <el-upload ref="uploadRef" action="" :disabled="props.disabled" :accept="props.accept" :auto-upload="false" :on-change="changeUpload" :on-remove="remove">
      <template #default>
        <el-button type="default" :disabled="props.disabled">{{isShow?'重新选择':'选择文件'}}</el-button>
      </template>
    </el-upload>
    <span class="download" v-show="!props.disabled" :class="{disabled}" @click="download(props.source)">下载模版</span>
  </div>
</template>
<script setup lang="tsx">
  import { reactive, ref, watch, computed } from 'vue'
  import { uploadFile2 } from '@/api/common'
  import type { UploadInstance } from 'element-plus'
  import { downloadCommon } from '@/api/ecommerce/tradingManage'
  import { downloadFile } from '@/utils/utils'

  const uploadRef = ref<UploadInstance>()
  const isShow = ref(false)
  interface Props {
    modelValue: string
    accept: string
    disabled: boolean
    source: number|string
  }
  const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    accept: '.xls,.xlsx',
    disabled: false,
    source: ''
  })
  const emit = defineEmits(['update:modelValue', 'change'])

  const changeUpload = async (file: any, fileList: any) => {
    if (fileList.length > 1) {
      fileList.splice(0, 1)
    }
    const params = { file: file.raw, fileName: file.name }
    const { code: code = '' }: any = await uploadFile2(params)
    code ? isShow.value = true : isShow.value = false
    !!code && emit('update:modelValue', code)
    !!code && emit('change', code)
  }
  const remove = () => {
    emit('update:modelValue', '')
  }

  const download = async (type: any) => {
    if(props.disabled) return
    const { url: url = '' } = await downloadCommon({module:'order',type: type})
    console.log('url - -   ', url)
    url && downloadFile(url)
  }
</script>
<style scoped lang="scss">
  .upload {
    position: relative;
    .download {
      position: absolute;
      top: 0;
      left: 100px;
      color: #ff6b00;
      font-size: 13px;
      cursor: pointer;
    }
    .download-tMall {
      left: 200px;
    }
    .disabled{
      color: #999;
      cursor: not-allowed;
    }
  }
</style>
